package com.jacklei.ch16;

import com.jacklei.ch15.TreeNode;
import org.omg.PortableInterceptor.INACTIVE;
import org.w3c.dom.ls.LSInput;
import sun.reflect.generics.tree.Tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/*
* 给定一个二叉搜索树的根节点 root ，和一个整数 k ，请你设计一个算法查找其中第 k 个最小元素（从 1 开始计数）。

 

示例 1：


输入：root = [3,1,4,null,2], k = 1
输出：1
示例 2：


输入：root = [5,3,6,2,4,null,null,1], k = 3
输出：3
 

 

提示：

树中的节点数为 n 。
1 <= k <= n <= 104
0 <= Node.val <= 104

来源：力扣（LeetCode）
链接：https://leetcode.cn/problems/kth-smallest-element-in-a-bst
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。*/
public class KthSmallestElementInABst {
    public static void main(String[] args) {
        KthSmallestElementInABst k = new KthSmallestElementInABst();
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(1);
        root.right = new TreeNode(4);
        root.left.right = new TreeNode(2);
        System.out.println(k.kthSmallest(root, 1));
    }
    public int kthSmallest1(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack();
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root =  root.left;
            }
            root = stack.pop();
            k--;
            if(k == 0)
                break;
            root = root.right;
        }
        return root.val;
    }

    public int kthSmallest(TreeNode root, int k) {
        List<Integer> list = new ArrayList<>();
        f(root,list,k);
        return list.get(k-1);
    }
    public void f (TreeNode root, List<Integer> list,int k){
        if (root == null) return;
        if(list.size() == k) return;
        f(root.left,list,k);
        list.add(root.val);
        f(root.right,list,k);
    }
    public static class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }


}
